package com.zHan.service.impl;

import com.zHan.dto.RegisterDto;
import com.zHan.exception.BaseException;
import com.zHan.mapper.UserMapper;
import com.zHan.pojo.Result;
import com.zHan.pojo.User;
import com.zHan.service.UserService;
import com.zHan.utils.Md5Util;
import com.zHan.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Map;

/**
 * ClassName: UserServiceImpl
 * Description:
 * date: 2023/11/7 0007 20:37
 *
 * @author zHan
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    /**
     * 根据用户名查询用户
     *
     * @param username
     * @return
     */
    @Override
    public User findByUsername(String username) {
        return userMapper.selectByUserName(username);
    }

    /**
     * 用户注册
     *
     * @param dto
     * @return
     */
    @Override
    public Result register(RegisterDto dto) {
        String password = dto.getPassword();
        // 密码md5加密
        String username = dto.getUsername();
        String md5Password = Md5Util.getMD5String(password);
        // 用户注册
        userMapper.register(username, md5Password);
        return Result.success();
    }

    /**
     * 更新用户信息
     *
     * @param user
     * @return
     */
    @Override
    public Result update(User user) {
        user.setUpdateTime(LocalDateTime.now());
        userMapper.update(user);
        return Result.success("用户信息更新成功");
    }

    /**
     * 更新用户头像
     *
     * @param avatarUrl
     * @return
     */
    @Override
    public Result updateAvatar(String avatarUrl) {
        // 获取用户id，并查询用户
        Map<String, Object> claims = ThreadLocalUtil.get();
        Integer id = (Integer) claims.get("id");
        if (id == null) {
            throw new BaseException("id不存在");
        }
        // 更新头像
        userMapper.updateAvatar(id, avatarUrl);
        return Result.success("用户头像更新成功");
    }

    /**
     * 更新用户密码
     *
     * @param newPwd
     * @return
     */
    @Override
    public void updatePwd(String newPwd) {
        // 获取用户id，并查询用户
        Map<String, Object> claims = ThreadLocalUtil.get();
        Integer id = (Integer) claims.get("id");
        // md5加密
        String password = Md5Util.getMD5String(newPwd);
        // 更新密码
        userMapper.updatePwd(id, password);
    }
}
